package com.gxa.controller;

import com.gxa.dto.ResultDto;
import com.gxa.pojo.User;
import com.gxa.service.UserService;
import com.gxa.util.MD5Util;
import com.gxa.util.Response;
import com.gxa.validate.MyValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/index")
@Transactional(rollbackFor = Throwable.class)
public class IndexController {

    @Autowired
    private MyValidator validator;

    @Autowired
    private UserService userService;

    @GetMapping("/page")
    public String loginPage(){
        return "index";
    }

    @GetMapping("/welcome")
    public String welcomePage(){
        return "welcome";
    }

    @GetMapping("/changePasswordPage")
    public String changePasswordPage(){
        return "changePasswordPage";
    }

    /**
     * 修改密码
     * @param user
     * @param oldPassword
     * @param session
     * @return
     */
    @PostMapping("/changePassword")
    @ResponseBody
    public ResultDto changePassword(User user, String oldPassword, HttpSession session){
        validator.validate(user);
        if (user.getUserId() == null || oldPassword == null){
            return Response.error(1001, "数据参数有误！");
        }
        if (oldPassword!=null && !oldPassword.equals("")) {
            User user1 = userService.findByPK(user.getUserId());
            if (!user1.getUserPassword().equals(MD5Util.MD55(oldPassword))) {
                return Response.error(1002, "原密码输入错误！");
            }
            user.setUserPassword(MD5Util.MD55(user.getUserPassword()));
        }
        Integer update = userService.update(user);
        if (update<=0){
            return Response.error(1002, "修改失败！");
        }
        User byPK = userService.findByPK(user.getUserId());
        session.setAttribute("user", byPK);
        return Response.success("修改成功！");
    }

    /**
     * 登出操作
     * @param session
     * @return
     */
    @RequestMapping("/loginOut")
    public String loginOut(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/login/byNamePage";
    }
}
